package com.andy.blog.admin.service.impl;

import com.andy.blog.admin.dto.SysMenuDTO;
import com.andy.blog.admin.dto.TreeSelectDTO;
import com.andy.blog.admin.service.SysMenuBusService;
import com.andy.blog.common.constant.BaseConstants;
import com.andy.blog.common.constant.UserConstants;
import com.andy.blog.common.exception.BlogServiceException;
import com.andy.blog.common.utils.SecurityUtils;
import com.andy.blog.common.utils.StringUtils;
import com.andy.blog.common.utils.TransformUtils;
import com.andy.blog.dal.domain.SysMenuDO;
import com.andy.blog.dal.domain.SysRoleDO;
import com.andy.blog.dal.domain.vo.MetaVo;
import com.andy.blog.dal.domain.vo.RouterVo;
import com.andy.blog.dal.service.SysMenuDalService;
import com.andy.blog.dal.service.SysRoleDalService;
import com.andy.blog.dal.vo.SysMenuVO;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.andy.blog.common.utils.SecurityUtils.getUserId;

/**
 * Created by andy on 2023/6/27 11:18
 */
@Service
public class SysMenuBusServiceImpl implements SysMenuBusService {

    @Resource
    private SysMenuDalService sysMenuDalService;

    @Resource
    private SysRoleDalService sysRoleDalService;


    @Override
    public List<SysMenuDTO> selectMenuList(SysMenuVO sysMenuVO) {
        Long userId = getUserId();
        List<SysMenuDO> menuList;
        // 管理员显示所有菜单信息
        if (SecurityUtils.isAdmin(userId)) {
            menuList = sysMenuDalService.selectMenuListByUserId(sysMenuVO, null);
        } else {
            menuList = sysMenuDalService.selectMenuListByUserId(sysMenuVO, userId);
        }

        return TransformUtils.transformList(menuList, SysMenuDTO.class);
    }

    @Override
    public void removeMenuById(Long menuId) {
        if (sysMenuDalService.hasChildByMenuId(menuId)) {
            throw new BlogServiceException("存在子菜单,不允许删除");
        }
        if (sysMenuDalService.checkMenuExistRole(menuId)) {
            throw new BlogServiceException("菜单已分配,不允许删除");
        }

        sysMenuDalService.deleteMenuById(menuId);
    }

    @Override
    public void edit(SysMenuVO sysMenuVO) {
        if (Objects.equals(sysMenuVO.getId(), sysMenuVO.getParentId())) {
            throw new BlogServiceException("修改菜单[" + sysMenuVO.getMenuName() + "]失败，上级菜单不能选择自己");
        }

        boolean menuNameUnique = sysMenuDalService.checkMenuNameUnique(sysMenuVO);
        if (Boolean.FALSE.equals(menuNameUnique)) {
            throw new BlogServiceException("修改菜单[" + sysMenuVO.getMenuName() + "]失败，菜单名称已存在");
        }

        if (UserConstants.YES_FRAME.equals(sysMenuVO.getIsFrame() + "") && !StringUtils.ishttp(sysMenuVO.getPath())) {
            throw new BlogServiceException("修改菜单[" + sysMenuVO.getMenuName() + "]失败，地址必须以http(s)://开头");
        }

        sysMenuDalService.updateMenu(sysMenuVO);
    }

    @Override
    public void add(SysMenuVO sysMenuVO) {
        if (Boolean.FALSE.equals(sysMenuDalService.checkMenuNameUnique(sysMenuVO))) {
            throw new BlogServiceException("新增菜单[" + sysMenuVO.getMenuName() + "]失败，菜单名称已存在");
        }

        if (UserConstants.YES_FRAME.equals(sysMenuVO.getIsFrame() + "") && !StringUtils.ishttp(sysMenuVO.getPath())) {
            throw new BlogServiceException("新增菜单[" + sysMenuVO.getMenuName() + "]失败，地址必须以http(s)://开头");
        }
        sysMenuDalService.insertMenu(sysMenuVO);
    }

    @Override
    public Map<String, Object> roleMenuTreeSelect(Long roleId) {
        Map<String, Object> ajax = new HashMap<>();
        SysRoleDO role = sysRoleDalService.selectRoleById(roleId);
        ajax.put("checkedKeys", sysMenuDalService.selectMenuListByRoleId(roleId, role.getMenuCheckStrictly()));
        ajax.put("menus", this.buildMenuTreeSelect(new SysMenuVO()));
        return ajax;
    }

    @Override
    public SysMenuDTO selectMenuById(Long id) {
        SysMenuDO sysMenuDO = sysMenuDalService.selectMenuById(id);
        return TransformUtils.transform(sysMenuDO, SysMenuDTO.class);
    }

    @Override
    public List<TreeSelectDTO> buildMenuTreeSelect(SysMenuVO sysMenuVO) {
        List<SysMenuDTO> sysMenuDTOS = this.selectMenuList(sysMenuVO);
        List<SysMenuDTO> menuTrees = buildMenuTree(sysMenuDTOS);
        return menuTrees.stream().map(TreeSelectDTO::new).collect(Collectors.toList());
    }

    @Override
    public List<SysMenuDTO> selectMenuTreeByUserId(Long userId) {
        List<SysMenuDO> menus;
        if (SecurityUtils.isAdmin(userId)) {
            menus = sysMenuDalService.selectMenuTreeAll();
        } else {
            menus = sysMenuDalService.selectMenuTreeByUserId(userId);
        }
        List<SysMenuDTO> sysMenuDTOS = TransformUtils.transformList(menus, SysMenuDTO.class);
        return getChildPerms(sysMenuDTOS, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenuDTO> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenuDTO menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), 1 == menu.getIsCache(), menu.getPath()));
            List<SysMenuDTO> cMenus = menu.getChildren();
            if (CollectionUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(org.apache.commons.lang3.StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), 1 == menu.getIsCache(), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(org.apache.commons.lang3.StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     */
    public String getRouteName(SysMenuDTO menuDTO) {
        String routerName = org.apache.commons.lang3.StringUtils.capitalize(menuDTO.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menuDTO)) {
            routerName = org.apache.commons.lang3.StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuDTO menu) {
        String component = UserConstants.LAYOUT;
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (org.apache.commons.lang3.StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (org.apache.commons.lang3.StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuDTO menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuDTO menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.INT_NO_FRAME == menu.getIsFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }


    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuDTO menu) {
        return (menu.getIsFrame() == UserConstants.INT_NO_FRAME) && com.andy.blog.common.utils.StringUtils.ishttp(menu.getPath());
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return org.apache.commons.lang3.StringUtils.replaceEach(path, new String[]{BaseConstants.HTTP, BaseConstants.HTTPS, BaseConstants.WWW, "."},
                new String[]{"", "", "", "/"});
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuDTO menu) {
        return menu.getParentId().intValue() == 0 &&
                UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame() == UserConstants.INT_NO_FRAME;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuDTO> getChildPerms(List<SysMenuDTO> list, int parentId) {
        List<SysMenuDTO> returnList = new ArrayList<>();
        for (SysMenuDTO t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }


    /**
     * 构建菜单🌲
     */
    public List<SysMenuDTO> buildMenuTree(List<SysMenuDTO> menus) {
        List<SysMenuDTO> returnList = Lists.newArrayList();
        List<Long> tempList = menus.stream().map(SysMenuDTO::getId).collect(Collectors.toList());
        for (SysMenuDTO menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<SysMenuDTO> list, SysMenuDTO t) {
        // 得到子节点列表
        List<SysMenuDTO> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenuDTO tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenuDTO> getChildList(List<SysMenuDTO> list, SysMenuDTO t) {
        List<SysMenuDTO> tlist = Lists.newArrayList();
        for (SysMenuDTO n : list) {
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuDTO> list, SysMenuDTO t) {
        return !getChildList(list, t).isEmpty();
    }
}
